package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
	"time"
)

func main() {
	//解析命令行参数
	port := flag.Int("port", 8080, "port number")
	flag.Parse()
	server, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))

	if err != nil {
		fmt.Fprintf(os.Stderr, "err: %v", err)
	}

	for {
		client, err := server.Accept()
		if err != nil {
			fmt.Fprintf(os.Stderr, "err: %v", err)
		}
		//
		go HandleClient(client)

	}
}

func HandleClient(c net.Conn) error {
	defer c.Close()

	for {
		_, err := io.WriteString(c, time.Now().Format("15:04:05\n"))
		if err != nil {
			fmt.Fprintf(os.Stderr, "[client:%v] has exit", c.LocalAddr())
			return err
		}
		time.Sleep(1 * time.Second)
	}
}
